<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :areas="treeAreas" :area-type="areaType"  v-on:handleNodeClick="onHandleNodeClick" />
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-date-picker
              style="margin-left: 20px;"
              class="filter-item"
              v-model="listQuery.date"
              type="daterange"
              :picker-options="pickerOptions"
              :clearable="false"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
            <el-button   style="margin-left:40px" class="filter-item" type="primary" icon="el-icon-search" @click="fetchList">
              查询
            </el-button>
            <el-button  :loading="exportLoading" style="margin-left:40px" class="filter-item" type="primary" icon="el-icon-download" @click="exportData">
              导出
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              v-loading="listLoading"
              :data="list"
              ref="waterTable"
              :row-style="{height:40+'px'}"
              :cell-style="{padding:0+'px'}"
              border
              fit
              stripe
              highlight-current-row
              height="700"
              style="width: 100%;"
            >
              <el-table-column
                type="index"
                label="#"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column label="区域" align="center" >
                <template v-slot="{row}">
                  <span>{{row.area_name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="设备总数" align="center"  >
                <template v-slot="{row}">
                  <span>{{ row.device_count}}</span>
                </template>
              </el-table-column>
              <el-table-column label="抄收成功" align="center" >
                <template v-slot="{row}">
                  <span>{{row.meter_count }}</span>
                </template>
              </el-table-column>
              <el-table-column label="抄收失败" align="center" >
                <template v-slot="{row}">
                  <span>{{row | formatFailedCount }}</span>
                </template>
              </el-table-column>
              <el-table-column  label="累计水量(m³)"  align="center">
                <template v-slot="{row}">
                  <span>{{row.meter_amount.toFixed(2)}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import Pagination from '@/components/Pagination'
import {getAreaTree} from "@/api/area";
import {checkPermission} from "@/utils/permission";
import moment from "moment";
import {customerFeeReport, meterReport} from "@/api/analysis";
import {getCustomerTypeText} from "@/utils";
import {exportExcel} from "@/utils/excel";

export default {
  name: 'MeterReport',
  components:{areas,Pagination},
  data() {
    return {
      tableKey:0,
      exportLoading:false,
      listLoading:true,
      list:[],
      total:0,
      areaType:1,
      dateType:'daterange',
      pickerOptions: {
        disabledDate: time => {
          const now = new Date();
          const thirtyDaysLater = new Date(now.getFullYear(), now.getMonth(), now.getDate());
          return time.getTime() > thirtyDaysLater;
        },
        onPick: ({ minDate, maxDate }) => {
          if (minDate && !maxDate) {
            this.$nextTick(() => {
              this.pickerOptions.disabledDate = time => {
                return time.getTime() < minDate.getTime() - 3600 * 1000 * 24 || time.getTime() > minDate.getTime() + 3600 * 1000 * 24 * 30;
              };
            });
          } else {
            this.pickerOptions.disabledDate = () => {
              return false;
            };
          }
        }
      },
      listQuery:{
        date: [],
        area_type:1,
        start_date: '',
        end_date: '',
        code:'',
        is_contains_sub: this.$store.getters.showSubData,
        page:1,
        pageSize:20
      },
      treeAreas:[],
      types:[
        { label: '年报', value: 'year'},
        { label: '月报', value: 'month' },
        { label: '日报', value: 'date' },
      ],
    }
  },
  filters: {
    formatFailedCount(row){
      const val = row.device_count - row.meter_count
      return val >=0 ? val:0
    }
  },
  created() {
    this.listQuery.date =  [moment().subtract(30, 'days').toDate(), moment().toDate()]
    this.fetchList()
    this.getAreaTree()
  },
  methods: {
    checkPermission,
    getAreaTree(type){
      getAreaTree({type:2,is_contains_sub:this.$store.getters.showSubData}).then(response => {
        this.treeAreas = response.data
      })
    },
    onHandleNodeClick:function (data) {
      if(this.listQuery.code !== data.code){
        this.listQuery.code = data.code
        this.fetchList()
      }
    },
    fetchList(){
      this.listLoading = true
      let data = Object.assign({},this.listQuery)
      if(data.date.length < 2) {
        this.$message.error("请选择时间")
        return
      }
      data.start_date = moment(data.date[0]).format('yyyy-MM-DD')
      data.end_date = moment(data.date[1]).format('yyyy-MM-DD')
      meterReport(data).then(response => {
        if(response.code === 20000) {
          this.list = response.data.list
          this.total = response.data.total
        }

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    exportData(){
      this.exportLoading = true
      let data = Object.assign({},this.listQuery)
      if(data.date.length < 2) {
        this.$message.error("请选择时间")
        return
      }
      data.start_date = moment(data.date[0]).format('yyyy-MM-DD')
      data.end_date = moment(data.date[1]).format('yyyy-MM-DD')
      meterReport(data).then(response => {
        if(response.code === 20000) {
          const headers = [
            '区域',
            '设备总数',
            '抄收成功',
            '抄收失败',
            '累计水量(m³)',
          ]
          const list = response.data.list.map(item => {
            let failedCount = item.device_count - item.meter_count
            failedCount = failedCount >=0? failedCount:0
            return {
              '区域': item.area_name,
              '设备总数': item.device_count,
              '抄收成功': item.meter_count,
              '抄收失败': failedCount,
              '累计水量(m³)': item.meter_amount.toFixed(2),
            }
          })
          exportExcel(list, headers, '抄表统计')
          this.exportLoading = false
        }
      })
    },
    resetQueryParams(){
      this.listQuery = {
        date: null,
        code:'',
        page:1,
        pageSize:20
      }
    }
  }
}
</script>
